package com.wpf.system.common.utils;

import cn.hutool.core.collection.CollUtil;
import com.wpf.system.service.OrdersService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;

@Component
public class OrderDelayService  implements InitializingBean {

    public static final String ORDER_DELAY_TASK_KEY = "OrderDelayQueue";

    //该类对象Bean实例化后，开启定时任务
    @Override
    @Scheduled(cron = "0/5 * * * * ?")
    public void afterPropertiesSet(){
        OrdersTimeStop();
    }

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private OrdersService ordersService;

    //以订单号为value,时间戳为score 保存至zSet
    public void OrdersTimeBegin(String orderSerialNo){
        redisUtils.setZSet(ORDER_DELAY_TASK_KEY,orderSerialNo,System.currentTimeMillis() + (10 * 60 * 1000));
    }

    //延时任务达到时效后关闭订单，并将延时任务从redis zSet删除
    @Async
    public void OrdersTimeStop(){
        Set<ZSetOperations.TypedTuple<String>> orderSerialNos = redisUtils.getZSet(ORDER_DELAY_TASK_KEY,0,System.currentTimeMillis());
        if (CollUtil.isNotEmpty(orderSerialNos)) {
            for (ZSetOperations.TypedTuple<String> orderSerialNo : orderSerialNos) {
                ordersService.checkOrdersPay(orderSerialNo.getValue());
                redisUtils.delZSet(ORDER_DELAY_TASK_KEY, orderSerialNo.getValue());
            }
        }
    }
}
